#include <unistd.h>
#include "linux/i2c-dev.h"
#include "sys/ioctl.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdint.h> 

int i2c_write(unsigned char slave_addr, unsigned char reg_addr,
    unsigned char length, unsigned char const *data) {
    // 使用Linux的I2C接口实现
    int fd = open("/dev/i2c-0", O_RDWR);
    if (fd < 0) {
        return -1;
    }

    if (ioctl(fd, I2C_SLAVE, slave_addr) < 0) {
        printf("i2c_write error - ioctl failure\n");
        close(fd);
        return -1;
    }
    
    uint8_t buf[length + 1];

    buf[0] = reg_addr;
    memcpy(buf + 1, data, length);
    if (write(fd, buf, length + 1) != length + 1) {
        printf("i2c_write error - write failure\n");
        close(fd);
        return -1;
    }
    close(fd);
    return 0;
}

int i2c_read(unsigned char slave_addr, unsigned char reg_addr,
   unsigned char length, unsigned char *data) {
    // 使用Linux的I2C接口实现
    int fd = open("/dev/i2c-0", O_RDWR);
    if (fd < 0) {
        return -1;
    }
    if (ioctl(fd, I2C_SLAVE, slave_addr) < 0) {
        close(fd);
        return -1;
    }
    if (write(fd, &reg_addr, 1) != 1) {
        close(fd);
        return -1;
    }
    if (read(fd, data, length) != length) {
        close(fd);
        return -1;
    }
    close(fd);
    return 0;
}